import store from '../store';
import Layout from '../views/layout';

// routes
import exampleRoute from './example';
import baseComponentRoute from './base-component';
import toolExampleRoute from './tool-example';

export function lazyLoadView(AsyncView) {
  const AsyncHandler = () => ({
    component: AsyncView,
    // 加载组件时使用的组件。
    // loading: require('../views/_loading').default,
    // 延迟显示加载组件。
    // 默认: 200 (milliseconds).
    delay: 400,
    // 在加载组件时超时的情况下的回退组件。
    // error: require('@views/_timeout').default,
    // 在放弃加载组件之前的时间。
    // 默认: Infinity (milliseconds).
    timeout: 10000,
  });

  return Promise.resolve({
    functional: true,
    render(h, { data, children }) {
      // 放弃将组件加载到视图组件之前的时间。
      return h(AsyncHandler, data, children);
    },
  });
}

export const mainRoutes = [
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/home'),
    meta: {
      isAuth: true,
      label: '首页',
      icon: 'el-icon-s-home',
      breadcrumb: [{ label: '首页' }],
    },
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('../views/dashboard'),
    meta: {
      isAuth: true,
      label: '报表',
      icon: 'el-icon-s-data',
      breadcrumb: [{ label: '报表' }],
    },
  },
  exampleRoute,
  baseComponentRoute,
  toolExampleRoute,
];

export default [
  {
    path: '',
    component: Layout,
    redirect: 'home',
    children: mainRoutes,
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login'),
    meta: {
      beforeResolve(routeTo, routeFrom, next) {
        // 如果当前用户登录状态存在，则重定向到 home 页面
        if (store.getters['user/isLogin']) {
          next({ name: 'home' });
        } else {
          // Continue to the login page
          next();
        }
      },
    },
  },
  {
    path: '/404',
    name: '404',
    component: require('../views/_404').default,
    // Allows props to be passed to the 404 page through route
    // params, such as `resource` to define what wasn't found.
    props: true,
  },
  {
    path: '*',
    redirect: '404',
  },
];
